package com.campus.common.filter;


import com.campus.common.domain.LoginUser;
import com.campus.common.utils.JwtUtil;
import com.campus.common.utils.RedisCache;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
@Component
@Slf4j
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        // 如果有token便解析
        if(StringUtils.hasText(token)) {
            LoginUser loginUser = null;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                int userId = Integer.parseInt(claims.getSubject());
                if(userId != 0) {
                    loginUser = redisCache.getCacheObject("loginUser:id: " + userId);
                }
            }catch (Exception e)
            {
                e.printStackTrace();
                filterChain.doFilter(request,response);
                return;
            }
            if(loginUser != null) {
                log.info(loginUser.getUserDto().toString());
                PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(loginUser.getUserDto(),null,loginUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request,response);
    }
}
